<!--
 * @Author: cgl
 * @Date: 2023-04-20 15:43:59
 * @LastEditors: liangkun 2669681641@qq.com
 * @LastEditTime: 2023-12-08 09:03:11
 * @FilePath: \radiation-hygiene-fe\src\views\person\person.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="100px"
    >
      <el-row>
        <el-col :span="5">
          <el-form-item label="单位名称" label-width="80px">
            <m-select
              v-model="queryParams.entrustOrganizationId"
              placeholder="输入文字检索查询"
              style="width: 100%"
              filterable
              clearable
              :lists="entrustOrganizationSelect"
              lists_label="organizationName"
              lists_value="entrustOrganizationId"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="手机号">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="名字" label-width="80px">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入"
              clearable
              @keyup.enter.native="getList()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.state"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in dict.type.work_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="tableoperation">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click.native.prevent="openDialog()"
        >添加</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-download"
        size="mini"
        @click.native.prevent="handleDownloadTemplate()"
        >下载模板</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-upload2"
        size="mini"
        plain
        @click.native.prevent="handleImport()"
        >导入</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-download"
        size="mini"
        plain
        @click.native.prevent="exportPeople()"
        >人员导出</el-button
      >
      <el-button
        type="danger"
        icon="el-icon-delete"
        size="mini"
        :disabled="selection.length == 0"
        plain
        @click.native.prevent="handleAllDelete()"
        >删除</el-button
      >
      <el-button
        style="float: right"
        :disabled="selection.length != 1"
        type="primary"
        icon="el-icon-upload"
        size="mini"
        @click.native.prevent="openUploadCer()"
        >上传证书</el-button
      >
      <el-button
        style="float: right"
        :disabled="selection.length != 1"
        type="primary"
        icon="el-icon-upload"
        size="mini"
        @click.native.prevent="openUploadExam()"
        >上传体检单</el-button
      >
    </div>

    <el-table
      v-loading="loading"
      :data="entrustWorkingPersonnelList"
      :height="height - 400 + 'px'"
      @selection-change="handleSelectionChange"
      @row-dblclick="(row) => openDialog(row, '3')"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="单位名称"
        align="center"
        prop="entrustOrganizationName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="姓名" align="center" prop="name" width="100" />
      <el-table-column label="性别" align="center" width="50">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column
        label="职业分类"
        align="center"
        prop="occupationalClassificationName"
        width="160"
      />
      <el-table-column label="状态" align="center" width="50">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.work_status" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" width="50" />
      <el-table-column
        label="从业开始时间"
        align="center"
        prop="employmentTime"
        width="110"
      />
      <el-table-column
        label="手机号"
        align="center"
        prop="mobile"
        width="110"
      />
      <el-table-column label="铅衣穿戴" align="center" width="90">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.is_or_no"
            :value="scope.row.wearLeadCoat"
          />
        </template>
      </el-table-column>
      <el-table-column label="剂量编号" align="center" prop="dosageNumber" />
      <el-table-column
        label="铅衣内编号"
        align="center"
        prop="dosageNumberWithin"
      />
      <el-table-column
        label="铅衣外编号"
        align="center"
        prop="dosageNumberOutside"
      />
      <el-table-column label="体检信息" align="center">
        <template slot-scope="{ row }">
          <el-button
            :disabled="!row.examinationCount || row.examinationCount == 0"
            type="primary"
            size="mini"
            plain
            @click="openExamList(row)"
          >
            <span v-if="row.examinationCount && row.examinationCount != 0"
              >体检单({{ row.examinationCount }})张</span
            >
            <span v-else>无体检单</span>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="证书情况" align="center">
        <template slot-scope="{ row }">
          <el-button
            :disabled="!row.calibrationCount || row.calibrationCount == 0"
            type="primary"
            size="mini"
            plain
            @click="openCerList(row)"
          >
            <span v-if="row.calibrationCount && row.calibrationCount != 0"
              >证书({{ row.calibrationCount }})本</span
            >
            <span v-else>无证书</span>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column align="center" label="操作">
        <template slot-scope="{ row }">
          <el-button @click.native.prevent="openDialog(row)" type="text">
            编辑
          </el-button>
          <el-button
            @click.native.prevent="handleDelete(row)"
            type="text"
            style="color: #f32d2d"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 人员弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="1000px"
      v-dialogDrag="true"
    >
      <el-form
        :model="form"
        :disabled="status == '3'"
        :rules="rules"
        ref="form"
        size="small"
        label-width="100px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="单位名称" prop="entrustOrganizationId">
              <m-select
                v-model="form.entrustOrganizationId"
                :dimStr="form.entrustOrganizationName"
                placeholder="请选择"
                filterable
                clearable
                style="width: 100%"
                :lists="entrustOrganizationSelect"
                lists_label="organizationName"
                lists_value="entrustOrganizationId"
                lists_key="entrustOrganizationId"
                :total="orgTotal"
                :pageSize="10"
                @handleChange="listeningEvent"
              >
              </m-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="人员编号" prop="personnelNumber">
              <el-input
                v-model="form.personnelNumber"
                placeholder="请输入人员编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-select
                v-model="form.sex"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="state">
              <el-select
                v-model="form.state"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.work_status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idCard">
              <el-input
                v-model="form.idCard"
                :placeholder="status != '3' ? '请输入' : ''"
                @blur="changeIdcard"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年龄" prop="age">
              <el-input
                v-model="form.age"
                :placeholder="status != '3' ? '请输入' : ''"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="mobile">
              <el-input
                v-model="form.mobile"
                :placeholder="status != '3' ? '请输入' : ''"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职业分类" prop="occupationalClassification">
              <el-select
                v-model="form.occupationalClassification"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.occupational_classification"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门">
              <el-input
                v-model="form.entrustDeptName"
                :placeholder="status != '3' ? '请输入' : ''"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职务">
              <el-input
                v-model="form.duties"
                :placeholder="status != '3' ? '请输入' : ''"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="从业开始时间">
              <el-date-picker
                style="width: 100%"
                v-model="form.employmentTime"
                value-format="yyyy-MM-dd"
                type="date"
                :placeholder="status != '3' ? '请选择' : ''"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="铅衣穿戴" prop="wearLeadCoat">
              <el-select
                v-model="form.wearLeadCoat"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.is_or_no"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.wearLeadCoat == '0'">
            <el-form-item label="剂量计编号">
              <el-input
                v-model="form.dosageNumber"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.wearLeadCoat == '1'">
            <el-form-item label="铅衣外编号">
              <el-input
                v-model="form.dosageNumberOutside"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.wearLeadCoat == '1'">
            <el-form-item label="铅衣内编号">
              <el-input
                v-model="form.dosageNumberWithin"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button type="primary" v-if="status != '3'" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 体检单弹框 -->
    <el-dialog
      :title="titleExam"
      :visible.sync="visibleExam"
      :close-on-click-modal="false"
      width="1000px"
      @close="closeExam"
      v-dialogDrag="true"
    >
      <el-form
        :model="formExam"
        :rules="rulesExam"
        ref="formExam"
        size="small"
        label-width="120px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名">
              <el-input v-model="formExam.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号">
              <el-input v-model="formExam.idCard" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-select v-model="formExam.sex" disabled>
                <el-option
                  v-for="item in dict.type.sys_user_sex"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="体检时间" prop="examinationTime">
              <el-date-picker
                style="width: 100%"
                v-model="formExam.examinationTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="图片上传" prop="ossId">
              <el-input v-model="formExam.ossId" v-if="false" />
              <div class="box">
                <div class="uploadname">
                  <span>已上传图片数：{{ fileList.length }}</span>
                </div>
                <el-upload
                  ref="upload"
                  class="avatar-uploader"
                  :action="upload.url"
                  :headers="upload.headers"
                  list-type="picture-card"
                  :file-list="fileList"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleFileSuccessSecond"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button type="primary" @click="submitFormExam">确 定</el-button>
        <el-button @click="visibleExam = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 证书弹框 -->
    <el-dialog
      ref="upload"
      :title="titleCer"
      :visible.sync="visibleCer"
      :close-on-click-modal="false"
      @close="closeExam"
      width="1000px"
      v-dialogDrag="true"
    >
      <el-form
        :model="formCer"
        :rules="rulesCer"
        ref="formCer"
        size="small"
        label-width="120px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名">
              <el-input v-model="formCer.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号">
              <el-input v-model="formCer.idCard" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-select v-model="formCer.sex" disabled>
                <el-option
                  v-for="item in dict.type.sys_user_sex"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="证书名称" prop="certificateName">
              <el-input
                v-model="formCer.certificateName"
                placeholder="请输入"
                disable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="证书编号" prop="certificateNumber">
              <el-input
                v-model="formCer.certificateNumber"
                placeholder="请输入"
                disable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职称">
              <el-input
                v-model="formCer.jobTitle"
                placeholder="请输入"
                disable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="签发日期">
              <el-date-picker
                style="width: 100%"
                v-model="formCer.signTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="培训开始日期">
              <el-date-picker
                style="width: 100%"
                v-model="formCer.cultivateCreateTime"
                value-format="yyyy-MM-dd"
                type="date"
                :picker-options="pickerOptionsF"
                placeholder="请选择"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="培训结束日期">
              <el-date-picker
                style="width: 100%"
                v-model="formCer.cultivateEndTime"
                value-format="yyyy-MM-dd"
                type="date"
                :picker-options="pickerOptionsS"
                placeholder="请选择"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片上传" prop="certificateOssId">
              <el-input v-model="formCer.certificateOssId" v-if="false" />
              <div class="box">
                <div class="uploadname">
                  <span>已上传图片数：{{ fileList.length }}</span>
                </div>
                <el-upload
                  ref="upload"
                  class="avatar-uploader"
                  :action="upload.url"
                  :headers="upload.headers"
                  list-type="picture-card"
                  :file-list="fileList"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleFileSuccessSecond"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button type="primary" @click="submitFormCer">确 定</el-button>
        <el-button @click="visibleCer = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 体检单列表弹框 -->
    <el-dialog
      title="查看体检单"
      :visible.sync="visibleExamList"
      :close-on-click-modal="false"
      width="1000px"
      v-dialogDrag="true"
    >
      <el-form
        disabled
        :model="formExamList"
        ref="form"
        size="small"
        label-width="100px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名">
              <el-input
                v-model="formExamList.name"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号">
              <el-input
                v-model="formExamList.idCard"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-select
                v-model="formExamList.sex"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in dict.type.sys_user_sex"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="formExamList.examList" height="400">
        <el-table-column label="序号" type="index" align="center" width="50">
          <template slot-scope="scope">
            <div style="text-align: center;">{{ scope.$index + 1 }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="体检时间"
          align="center"
          prop="examinationTime"
        />
        <el-table-column label="体检单" align="center">
          <template slot-scope="{ row }">
            <span v-if="row.sysOssVos && row.sysOssVos.length != 0">
              <el-image
                style="width: 100px; height: 100px"
                :src="row.sysOssVos[0].url"
                :preview-src-list="getUrl(row.sysOssVos)"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <span style="font-weight: bolder" v-if="row.sysOssVos.length > 1">
                ...</span
              >
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <el-button
              @click.native.prevent="openUploadExam(row, formExamList)"
              type="text"
            >
              编辑
            </el-button>
            <el-button
              @click.native.prevent="handleDeleteExam(row)"
              type="text"
              style="color: #f32d2d"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer">
        <el-button @click="visibleExamList = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 证书列表弹框 -->
    <el-dialog
      title="查看证书"
      :visible.sync="visibleCerList"
      :close-on-click-modal="false"
      width="1500px"
      v-dialogDrag="true"
    >
      <el-form
        disabled
        :model="formCerList"
        ref="form"
        size="small"
        label-width="100px"
      >
        <el-row :gutter="60">
          <el-col :span="7">
            <el-form-item label="姓名">
              <el-input
                v-model="formCerList.name"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="身份证号">
              <el-input
                v-model="formCerList.idCard"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="性别">
              <el-select
                v-model="formCerList.sex"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in dict.type.sys_user_sex"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="formCerList.cerList" height="400">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="证书名称" align="center">
          <template slot-scope="{ row }">
            <div class="imgitem" @click="viewImg(row.certificateOssId)">
              <span class="name">
                {{ row.certificateName }}
              </span>
              <span style="opacity: 0">
                <el-image
                  style="width: 100px; height: 100px"
                  src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
                  :preview-src-list="geturlList"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="证书编号"
          align="center"
          prop="certificateNumber"
        />
        <el-table-column label="职称" align="center" prop="jobTitle" />
        <el-table-column label="签发日期" align="center" prop="signTime" />
        <el-table-column label="培训开始时间" align="center">
          <template slot-scope="{ row }">
            {{ parseTime(row.cultivateCreateTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column label="培训结束时间" align="center">
          <template slot-scope="{ row }">
            {{ parseTime(row.cultivateEndTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column
          label="培训时长"
          align="center"
          prop="cultivateTotalTime"
        />
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <el-button
              @click.native.prevent="openUploadCer(row, formCerList)"
              type="text"
            >
              编辑
            </el-button>
            <el-button
              @click.native.prevent="handleDeleteCer(row)"
              type="text"
              style="color: #f32d2d"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer">
        <el-button @click="visibleCerList = false">关 闭</el-button>
      </div>
    </el-dialog>

    <div class="cusviewimgdialog" v-if="visibleImg">
      <img width="30%" :src="dialogImageUrl" alt="" />
      <span
        @click="visibleImg = false"
        class="el-image-viewer__btn el-image-viewer__close"
      >
        <i class="el-icon-close"></i>
      </span>
    </div>

    <!-- 列表导入对话框 -->
    <el-dialog
      :title="uploadList.title"
      :visible.sync="uploadList.open"
      width="400px"
      append-to-body
      @close="closeUpload"
      v-dialogDrag="true"
    >
      <el-upload
        ref="uploadList"
        :limit="1"
        :on-exceed="handleExceedList"
        accept=".xlsx, .xls"
        :headers="uploadList.headers"
        :action="uploadList.url"
        :disabled="uploadList.isUploading"
        :on-progress="handleFileUploadProgressList"
        :on-success="handleFileSuccessList"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileFormList">确 定</el-button>
        <el-button @click="uploadList.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  entrustWorkingPersonnelList,
  entrustWorkingPersonnelExport,
  entrustWorkingPersonnelDetail,
  downloadTemplate,
  entrustWorkingPersonnelAdd,
  importData,
  entrustWorkingPersonnelEdit,
  entrustWorkingPersonnelDelete,
  entrustWorkingPersonnelAllDelete,
  listByDosageNumber,
} from "@/api/person/person";
import {
  entrustWorkingPersonnelExaminationList,
  entrustWorkingPersonnelExaminationExport,
  entrustWorkingPersonnelExaminationDetail,
  entrustWorkingPersonnelExaminationAdd,
  entrustWorkingPersonnelExaminationEdit,
  entrustWorkingPersonnelExaminationDelete,
} from "@/api/person/personnelExamination";
import {
  listPersonCertificate,
  exportPersonCertificate,
  getPersonCertificate,
  addPersonCertificate,
  updatePersonCertificate,
  delPersonCertificate,
} from "@/api/person/personCertificate";
import { listOss, listByIds, delOss } from "@/api/system/oss";
import {
  entrustOrganizationListing,
  entrustOrganizationList,
} from "@/api/person/entrustOrganization";
import { getToken } from "@/utils/auth";
import MSelect from "@/components/mSelect";

export default {
  name: "User",
  components: { MSelect },
  dicts: [
    "sys_user_sex",
    "is_or_no",
    "work_status",
    "occupational_classification",
  ],
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      rules: {
        entrustOrganizationId: [
          { required: true, message: "单位名称不能为空", trigger: "change" },
        ],
        name: [{ required: true, message: "姓名不能为空", trigger: "change" }],
        sex: [{ required: true, message: "性别不能为空", trigger: "change" }],
        state: [{ required: true, message: "状态不能为空", trigger: "change" }],
        occupationalClassification: [
          { required: true, message: "职业分类不能为空", trigger: "change" },
        ],
        wearLeadCoat: [
          { required: true, message: "铅衣穿戴不能为空", trigger: "change" },
        ],
        idCard: [
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: "请输入正确的身份证号",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      rulesExam: {
        examinationTime: [
          { required: true, message: "体检时间不能为空", trigger: "change" },
        ],
        ossId: [{ required: true, message: "图片不能为空", trigger: "change" }],
      },
      rulesCer: {
        certificateName: [
          { required: true, message: "证书名称不能为空", trigger: "change" },
        ],
        certificateNumber: [
          { required: true, message: "证书编号不能为空", trigger: "change" },
        ],
      },
      // 视图高度
      height: document.documentElement.clientHeight,
      // 委托单位人员列表
      entrustWorkingPersonnelList: [],
      list: [
        { label: "1", value: "1" },
        { label: "2", value: "2" },
        { label: "3", value: "3" },
      ],
      dialogVisible: false,
      // 表单参数
      form: {},
      formExam: {},
      formCer: {},
      loading: false,
      status: null,
      title: null,
      visibleExam: false,
      visibleCer: false,
      visibleExamList: false,
      visibleCerList: false,
      formExamList: [],
      formCerList: [],
      titleExam: null,
      titleCer: null,
      openRowExam: {},
      openRowCer: {},
      statusExam: null,
      statusCer: null,
      // 勾选列表
      selection: [],
      // 体检单/证书导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
          "Content-Disposition": "inline",
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/oss/upload",
      },
      // 列表导入参数
      uploadList: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/basic/entrust/workingPersonnel/importData",
      },
      imageUrlS: "",
      visibleImg: false,
      dialogImageUrl: "",
      fileList: [],
      // 委托单位下拉框
      entrustOrganizationSelect: [],
      // 预览图片查询的url列表
      dialogImageUrlList: [],
      // 预览图片请求的url
      geturlList: [],
      // 日期校验
      pickerOptionsF: {
        disabledDate: (time) => {
          // return time.getTime() > Date.now();
          return (
            time.getTime() > new Date(this.form.cultivateEndTime).getTime()
          );
        },
      },
      pickerOptionsS: {
        disabledDate: (time) => {
          // return time.getTime() > Date.now();
          return (
            time.getTime() < new Date(this.form.cultivateCreateTime).getTime()
          );
        },
      },
      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
    };
  },
  created() {
    this.getList();
  },
  computed: {
    getUrl() {
      return (value) => {
        let list = [];
        list = value.map((item) => {
          return item.url;
        });
        return list;
      };
    },
  },
  methods: {
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.entrustOrganizationSelect.push(...response.rows);
        } else {
          this.entrustOrganizationSelect = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    // 获取人员列表
    getList() {
      this.queryParams.createTimeStart =
        this.queryParams.formDate && this.queryParams.formDate[0];
      this.queryParams.createTimeEnd =
        this.queryParams.formDate && this.queryParams.formDate[1];
      let queryParams = { ...this.queryParams };
      delete queryParams.formDate;
      this.loading = true;
      entrustWorkingPersonnelList(queryParams)
        .then((response) => {
          this.entrustWorkingPersonnelList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 打开对话框
    openDialog(row, status) {
      this.resetForm("form");
      if (status == "3") {
        /* 查看 */
        entrustWorkingPersonnelDetail(row.personnelId).then((response) => {
          this.form = response.data;
          this.dialogVisible = true;
        });
        this.status = "3";
        this.title = "查看人员";
      } else {
        if (row) {
          entrustWorkingPersonnelDetail(row.personnelId).then((response) => {
            this.form = response.data;
            if (!this.form.age && this.form.idCard) {
              this.changeIdcard({
                target: {
                  value: this.form.idCard,
                },
              });
            }
            this.dialogVisible = true;
          });
          this.status = "2";
          this.title = "编辑人员";
        } else {
          this.form = {
            state: "1",
            wearLeadCoat: "0",
          };
          this.status = "1";
          this.title = "添加人员";
          this.dialogVisible = true;
        }
      }
    },
    exportPeople() {
      if (!this.queryParams.entrustOrganizationId) {
        this.$modal.msgWarning("请选择筛选单位");
        return;
      }
      this.download(
        "/basic/entrust/workingPersonnel/export",
        {
          ...this.queryParams,
        },
        `人员信息.xlsx`
      );
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) return;
        if (this.status == "1") {
          entrustWorkingPersonnelAdd(this.form).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.dialogVisible = false;
            this.getList();
          });
        } else if (this.status == "2") {
          entrustWorkingPersonnelEdit(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.getList();
          });
        }
      });
    },
    submitFormExam() {
      this.formExam.ossId = this.fileList
        .map((item) => {
          if (item.ossId) {
            return item.ossId; /* 回显的列表格式 */
          } else if (item.response.data) {
            return item.response.data.ossId; /* 新上传的列表格式 */
          }
        })
        .join(",");
      console.log("this.formExam.ossId", this.formExam.ossId);
      this.$refs["formExam"].validate((valid) => {
        if (!valid) return;
        if (this.statusExam == "1") {
          this.formExam.personnelId = this.selection[0].personnelId;
          entrustWorkingPersonnelExaminationAdd(this.formExam).then(
            (response) => {
              this.$modal.msgSuccess("上传成功");
              this.visibleExam = false;
              this.getList();
            }
          );
        } else if (this.statusExam == "2") {
          entrustWorkingPersonnelExaminationEdit(this.formExam).then(
            (response) => {
              this.$modal.msgSuccess("编辑成功");
              this.visibleExam = false;
              this.openExamList(this.openRowExam); /* 刷新当前列表 */
              this.getList(); /* 刷新最外层列表 */
            }
          );
        }
      });
    },
    submitFormCer() {
      this.formCer.certificateOssId = this.fileList
        .map((item) => {
          if (item.ossId) {
            return item.ossId; /* 回显的列表格式 */
          } else if (item.response.data) {
            return item.response.data.ossId; /* 新上传的列表格式 */
          }
        })
        .join(",");
      this.$refs["formCer"].validate((valid) => {
        if (!valid) return;
        if (this.statusCer == "1") {
          this.formCer.personnelId = this.selection[0].personnelId;
          addPersonCertificate(this.formCer).then((response) => {
            this.$modal.msgSuccess("上传成功");
            this.visibleCer = false;
            this.getList();
          });
        } else if (this.statusCer == "2") {
          updatePersonCertificate(this.formCer).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.visibleCer = false;
            this.openCerList(this.openRowCer); /* 刷新当前列表 */
            this.getList(); /* 刷新最外层列表 */
          });
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
    },
    // 删除
    handleDelete(row) {
      this.$modal
        .confirm(`是否确认删除人员[${row.name}]？`)
        .then(() => {
          this.loading = true;
          let formData = new FormData();
          formData.append("personnelIds", row.personnelId);
          return entrustWorkingPersonnelAllDelete(formData);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 删除选中人员
    handleAllDelete() {
      if (this.selection.length == 0) {
        this.$modal.msgWarning("请选择人员");
        return;
      }
      const ids = this.selection.map((i) => i.personnelId);
      const names = this.selection.map((i) => i.name).join(",");
      this.$modal
        .confirm(`是否确认删除人员[${names}]？`)
        .then(() => {
          this.loading = true;
          let formData = new FormData();
          formData.append("personnelIds", ids);
          return entrustWorkingPersonnelAllDelete(formData);
        })
        .then(() => {
          this.loading = false;
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleDeleteExam(row) {
      this.$modal
        .confirm(`是否确认删除该体检单？`)
        .then(() => {
          return entrustWorkingPersonnelExaminationDelete(row.examinationId);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.openExamList(this.openRowExam);
        })
        .finally(() => {});
    },
    handleDeleteCer(row) {
      this.$modal
        .confirm(`是否确认删除该证书？`)
        .then(() => {
          return delPersonCertificate(row.certificateId);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.openCerList(this.openRowCer);
        })
        .finally(() => {});
    },
    // 下载模板
    handleDownloadTemplate() {
      this.download(
        "/basic/entrust/workingPersonnel/downloadTemplate",
        {},
        `外照射人员模板.xls`
      );
    },
    // 导出
    handleExport() {
      this.download(
        "/basic/entrust/workingPersonnel/export",
        {
          ...this.queryParams,
        },
        `外照射人员列表.xlsx`
      );
    },
    // 关闭导入
    closeUpload() {
      this.$refs.uploadList.clearFiles();
    },
    /** 导入按钮操作(列表) */
    handleImport() {
      this.uploadList.title = "导入";
      this.uploadList.open = true;
    },
    // 文件上传中处理(列表)
    handleFileUploadProgressList(event, file, fileList) {
      this.uploadList.isUploading = true;
    },
    // 文件上传成功处理(列表)
    handleFileSuccessList(response, file, fileList) {
      this.uploadList.open = false;
      this.uploadList.isUploading = false;
      this.$refs.uploadList.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 超出数量提示(列表)
    handleExceedList(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    // 提交上传文件(列表)
    submitFileFormList() {
      this.$refs.uploadList.submit();
    },
    // 身份证自动带出年龄
    changeIdcard(e) {
      let userCard = e.target.value;
      console.log("e", e);
      console.log("value", userCard);
      if (userCard.length == 15) {
        var org_birthday = userCard.substring(6, 12);
        //获取出生年月日
        var yearBirth = "19" + org_birthday.substring(0, 2);
        var monthBirth = org_birthday.substring(2, 4);
        var dayBirth = org_birthday.substring(4, 6);
      } else if (userCard.length == 18) {
        //获取出生年月日
        var yearBirth = userCard.substring(6, 10);
        var monthBirth = userCard.substring(10, 12);
        var dayBirth = userCard.substring(12, 14);
      } else {
        return;
      }
      //获取当前年月日并计算年龄
      var myDate = new Date();
      var monthNow = myDate.getMonth() + 1;
      var dayNow = myDate.getDate();
      var age = myDate.getFullYear() - yearBirth;
      if (
        monthNow < monthBirth ||
        (monthNow == monthBirth && dayNow < dayBirth)
      ) {
        age--;
      }
      //返回年龄
      this.$set(this.form, "age", age);
    },
    // 打开体检单
    openUploadExam(row, formExamList) {
      this.resetForm("formExam");
      if (row) {
        entrustWorkingPersonnelExaminationDetail(row.examinationId).then(
          (response) => {
            this.formExam = {
              ...response.data,
              name: formExamList.name /* 顺便展示人员信息 */,
              idCard: formExamList.idCard,
              sex: formExamList.sex,
            };
            if (response.data.sysOssVos) {
              this.fileList =
                response.data.sysOssVos &&
                response.data.sysOssVos.map((item) => {
                  return {
                    name: item.originalName,
                    url: item.url,
                    ossId: item.ossId,
                  };
                });
            }
            this.visibleExam = true;
          }
        );
        this.statusExam = "2";
        this.titleExam = "编辑体检单";
      } else {
        this.formExam = {
          ossId: null,
          ...this.selection[0] /* 顺便展示人员信息 */,
          examinationTime: null,
        };
        this.fileList = [];
        this.statusExam = "1";
        this.titleExam = "上传体检单";
        this.visibleExam = true;
      }
    },
    // 打开证书
    openUploadCer(row, formCerList) {
      this.resetForm("formCer");
      if (row) {
        getPersonCertificate(row.certificateId).then((response) => {
          this.formCer = {
            ...response.data,
            name: formCerList.name /* 顺便展示人员信息 */,
            idCard: formCerList.idCard,
            sex: formCerList.sex,
          };
          if (response.data.sysOssVos) {
            this.fileList = response.data.sysOssVos.map((item) => {
              return {
                name: item.originalName,
                url: item.url,
                ossId: item.ossId,
              };
            });
          }
          console.log("this.fileList", this.fileList);
          this.visibleCer = true;
        });
        this.statusCer = "2";
        this.titleCer = "编辑证书";
      } else {
        this.formCer = {
          certificateOssId: null,
          ...this.selection[0] /* 顺便展示人员信息 */,
        };
        this.fileList = [];
        this.statusCer = "1";
        this.titleCer = "上传证书";
        this.visibleCer = true;
      }
    },
    // 打开体检单列表
    openExamList(row) {
      this.openRowExam = row;
      console.log("row.personnelId", row.personnelId);
      entrustWorkingPersonnelExaminationList({
        personnelId: row.personnelId,
      }).then((response) => {
        this.formExamList = { ...row, examList: response.data };
        this.visibleExamList = true;
      });
    },
    // 打开证书列表
    openCerList(row) {
      this.openRowCer = row;
      listPersonCertificate({ personnelId: row.personnelId }).then(
        (response) => {
          this.formCerList = { ...row, cerList: response.data };
          this.visibleCerList = true;
        }
      );
    },
    // 关闭
    closeExam() {
      this.$refs.upload.clearFiles();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件移除
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    // 文件上传成功处理
    handleFileSuccessSecond(response, file, fileList) {
      if (response.code == 500) {
        this.$modal.msgWarning(response.msg);
      }
      this.fileList = fileList;
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 上传前
    beforeAvatarUpload(file) {
      let myisJPG = file.type === "image/jpeg" || file.type === "image/png";
      if (!myisJPG) {
        this.$message.warning("图片仅支持jpg/png格式，请重新上传!");
      }
      return myisJPG;
    },
    // 上传时的预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.visibleImg = true;
    },
    // 列表的预览图片
    viewImg(ossId) {
      this.geturlList = [];
      listByIds(ossId).then((response) => {
        this.geturlList = response.data.map((item) => item.url);
      });
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  border: 1px solid #dfdfdf;
  border-radius: 5px;
  padding: 10px;
}
.imgView {
  color: #2a72ee;
  cursor: pointer;
  margin-right: 10px;
  &:hover {
    text-decoration: underline;
  }
}
.imgcontainer {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  flex-wrap: wrap;
  img {
    width: 45%;
  }
}
.imgitem {
  position: relative;
  height: 20px;
  cursor: pointer;
  &:hover {
    .name {
      text-decoration: underline;
    }
  }
  .name {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    color: #2a72ee;
    cursor: pointer;
  }
}
</style>
